﻿using System.Linq.Expressions;
using Basic.FormDAL;
using Basic.FormModel.DB;
using Basic.FormRemoteModel;
using LinqKit;
using WeDonekRpc.Helper;

namespace Basic.FormCollect.lmpl
{
    internal class PhysicalColumnCollect : IPhysicalColumnCollect
    {
        private readonly IPhysicalColumnDAL _BasicDAL;

        public PhysicalColumnCollect ( IPhysicalColumnDAL basicDAL )
        {
            this._BasicDAL = basicDAL;
        }
        public Result Get<Result> ( long id ) where Result : class, new()
        {
            return this._BasicDAL.Get<Result>(id);
        }
        public void Clear ( long formId )
        {
            long[] ids = this._BasicDAL.Gets(a => a.FormId == formId, a => a.Id);
            if ( !ids.IsNull() )
            {
                this._BasicDAL.Delete(ids);
            }
        }
        public Result[] Gets<Result> ( long[] ids ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(ids);
        }

        public Result[] GetsByFormId<Result> ( long formId, FormColumnFuncType[] funcType, FormRecordDataType[] dataType ) where Result : class, new()
        {
            ExpressionStarter<DBPhysicalTableColumn> where = PredicateBuilder.New<DBPhysicalTableColumn>(a => a.FormId == formId);
            if ( !funcType.IsNull() )
            {
                where = where.And(a => funcType.Contains(a.FuncType));
            }
            if ( !dataType.IsNull() )
            {
                where = where.And(a => dataType.Contains(a.DataType));
            }
            return this._BasicDAL.Gets<Result>(where);
        }
        public Result[] GetsByTableId<Result> ( long tableId, FormColumnFuncType[] funcType, FormRecordDataType[] dataType, Expression<Func<DBPhysicalTableColumn, Result>> selector ) where Result : class, new()
        {
            ExpressionStarter<DBPhysicalTableColumn> where = PredicateBuilder.New<DBPhysicalTableColumn>(a => a.PhyTableId == tableId);
            if ( !funcType.IsNull() )
            {
                where = where.And(a => funcType.Contains(a.FuncType));
            }
            if ( !dataType.IsNull() )
            {
                where = where.And(a => dataType.Contains(a.DataType));
            }
            return this._BasicDAL.Gets<Result>(where, selector);
        }
    }
}
